<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Ldap
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: QueryResult.php 10 2008-11-08 17:17:02Z Stefan.Gehrig.HN $
 */

/** 
 * Zend_Ldap_Ext 
 */
require_once 'Zend/Ldap/Ext.php';
/** 
 * Zend_Ldap_Exception
 */
require_once 'Zend/Ldap/Exception.php';

/**
 * Zend_Ldap_QueryResult wraps query results.
 *
 * @category   Zend
 * @package    Zend_Ldap
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Ldap_QueryResult implements Iterator, Countable
{
	/**
	 * LDAP Connection
	 *
	 * @var Zend_Ldap
	 */
	protected $_ldap=null;
	
	/**
	 * Result identifier resource
	 *
	 * @var resource
	 */
	protected $_resultId=null;
	
	/**
	 * Current result entry identifier
	 *
	 * @var resource
	 */
	protected $_current=null;
	
	/**
	 * Current item number
	 *
	 * @var integer
	 */
	protected $_currentNumber=-1;
	
	/**
	 * Number of items in query result
	 *
	 * @var integer
	 */
	protected $_itemCount=-1;
	
	/**
	 * Container for item caching to speed up multiple iterations
	 *
	 * @var array
	 */
	protected $_cache=array();
	
	public function __construct(Zend_Ldap $ldap, $resultId)
	{
		$this->_ldap=$ldap;
		$this->_resultId=$resultId;
		$this->_itemCount=@ldap_count_entries($ldap->getResource(), $resultId);
		if ($this->_itemCount===false) 
		{
			throw new Zend_Ldap_Exception($this->_ldap, 'counting entries');
		}
	}
	
	public function __destruct()
	{
		$this->close();
	}
    
    /**
     * Closes the current result set
     *
     * @return bool
     */
    public function close()
    {
    	$isClosed=false;
    	if (is_resource($this->_resultId))
    	{
 			$isClosed=@ldap_free_result($this->_resultId);   		
    	}
    	return $isClosed;    	
    }
    
    /**
     * Get all entries as an array
     * 
     * @return array
     */
    public function toArray()
    {
    	$data=array();
        foreach ($this as $item)
        {
        	$data[]=$item;
        }
    	return $data; 
    }
    
	/**
     * Get first entry
     * 
     * @return array
     */
    public function getFirst()
    {
        if ($this->count()>0)
        {
        	$this->rewind();
        	return $this->current(); 
        }
        else return null;
    }
    
    /**
     * Returns the number of items in current result
     * Implements Countable
     *
     * @return int
     */
    public function count()
    {
    	return $this->_itemCount;
    }
    
    /**
	 * Return the current result item
	 * Implements Iterator
	 *
	 * @return array
	 * @throws Zend_Ldap_Exception
	 */
    public function current()
    {
    	if (!is_resource($this->_current)) return null;
    	$dn=@ldap_get_dn($this->_ldap->getResource(), $this->_current);
    	if ($dn===false) 
    	{
    		throw new Zend_Ldap_Exception($this->_ldap, 'getting dn');
    	}
    	
    	if (!array_key_exists($dn, $this->_cache))
    	{
			$entry=array('dn' => $dn);  		
			$name=@ldap_first_attribute($this->_ldap->getResource(), $this->_current);
			while ($name) 
			{
				$data=@ldap_get_values_len($this->_ldap->getResource(), $this->_current, $name);
				unset($data['count']);
				$entry[mb_strtolower($name, 'UTF-8')]=$data;
				$name=@ldap_next_attribute($this->_ldap->getResource(), $this->_current);
			}
			ksort($entry, SORT_LOCALE_STRING);
    		$this->_cache[$dn]=$entry;
    	}
    	return $this->_cache[$dn];
    }
    
	/**
	 * Return the result item key
	 * Implements Iterator
	 *
	 * @return int
	 */
	public function key()
    {
    	return $this->_currentNumber;
    }
    
	/**
	 * Move forward to next result item
	 * Implements Iterator
	 *
	 * @throws Zend_Ldap_Exception
	 */
	public function next()
    {
    	$this->_current=@ldap_next_entry($this->_ldap->getResource(), $this->_current);
    	if ($this->_current===false && 
    		ldap_errno($this->_ldap->getResource()) > Zend_Ldap_Exception::LDAP_SUCCESS) 
    	{
    		throw new Zend_Ldap_Exception($this->_ldap, 'getting next entry');
    	}
    	$this->_currentNumber++;
    }
    
	/**
	 * Rewind the Iterator to the first result item
	 * Implements Iterator
	 *
	 * @throws Zend_Ldap_Exception
	 */
	public function rewind()
    {
    	$this->_current=@ldap_first_entry($this->_ldap->getResource(), $this->_resultId);
    	if ($this->_current===false && 
    		ldap_errno($this->_ldap->getResource()) > Zend_Ldap_Exception::LDAP_SUCCESS) 
    	{
    		throw new Zend_Ldap_Exception($this->_ldap, 'getting first entry');
    	}
    	$this->_currentNumber=0;
    }
    
	/**
	 * Check if there is a current result item
	 * after calls to rewind() or next()
	 * Implements Iterator
	 *
	 * @return bool
	 */
	public function valid()
    {
    	return (is_resource($this->_current));
    }
}